package com.zhitong.ztblog.controllers;

import com.zhitong.ztblog.entity.Label;
import com.zhitong.ztblog.services.ILabelService;
import com.zhitong.ztblog.utils.AjaxResponse;
import org.apache.ibatis.annotations.Delete;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@CrossOrigin(origins = "*",maxAge = 3600)
@RestController
public class LabelContro {

    @Autowired
    private ILabelService labelService;

    @GetMapping("/randLabels")
    public AjaxResponse getByRand(){
        Label[] labels = labelService.findByRand();
        AjaxResponse success = AjaxResponse.success(labels);
        return success;
    }

    @GetMapping("/labels")
    public AjaxResponse getAll(){
        Label[] all = labelService.findAll();
        int labelNum = labelService.findLabelNum();
        Map<String,Object> map=new HashMap<>();
        map.put("labels",all);
        map.put("labelNum",labelNum);
        AjaxResponse success = AjaxResponse.success(map);
        return success;
    }
    
    @GetMapping("/labels/{bid}")
    public AjaxResponse getLabelsById(@PathVariable(name = "bid")int bid){
        Label[] labels = labelService.findByBid(bid);
        AjaxResponse success = AjaxResponse.success(labels);
        return success;
    }

    @GetMapping("/label/{id}")
    public AjaxResponse getLabelById(@PathVariable(name = "id")int id){
        Label label = labelService.findById(id);
        AjaxResponse success = AjaxResponse.success(label);
        return success;
    }

    @DeleteMapping("/label/{id}")
    public AjaxResponse delLabelById(@PathVariable(name = "id")int id){
        labelService.delLabelById(id);
        AjaxResponse success = AjaxResponse.success();
        return success;
    }



    @PostMapping("/label")
    public AjaxResponse insertLabel(@RequestBody Label label){
        int labelByName = labelService.findLabelNumByName(label);
        if (labelByName>0){
            AjaxResponse ajaxResponse=new AjaxResponse();
            ajaxResponse.setCode(500);
            ajaxResponse.setMessage("该标签已经存在!");
            return ajaxResponse;
        }else {
            labelService.insertLabel(label);
            AjaxResponse success = AjaxResponse.success();
            success.setMessage("添加成功");
            return success;
        }
    }

    @GetMapping("/labelnames/{bid}")
    public AjaxResponse getLabelNamesByBid(@PathVariable(name = "bid")int bid){
        String[] names = labelService.findNamesByBid(bid);
        AjaxResponse success = AjaxResponse.success(names);
        return success;
    }
}
